// app.js
require("./mixins.js")

const PubSub = require("./lib/PubSub");

App({
  require: (path) => require(path),
  globalData: {
    pubSub: new PubSub(),
    statusBarHeight: 0,
    message: {
      unreadNum: 0,
      watcher: null
    },
    config: {
      name: "oil社区",
      primaryColor: "#008080",
    }
  },
  onLaunch() {
    this.initCloud()
    this.getStatusBarHeight()
    this.watchMessage()
  },
  getStatusBarHeight() {
    // 获取状态栏高度
    const info = wx.getSystemInfoSync()
    this.globalData.statusBarHeight = info.statusBarHeight
  },
  watchMessage() {
    const { watchMessage } = require("./utils/request/message")
    const user = wx.getStorageSync('user')
    if (user && !this.globalData.message.watcher) {
      this.globalData.message.watcher = watchMessage(user._openid, (snapshot) => {
        this.changeUnreadNum(snapshot.docs.length)
      })
    }
  },
  changeUnreadNum(unreadNum) {
    this.globalData.message.unreadNum = unreadNum
    this.globalData.pubSub.publish("onMessage")
  },
  initCloud() {
    // 初始化云环境
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        env: 'oil-env-4gghoy230908c893',
        traceUser: true,
      });
    }
  }
});
